

const ajax = options => {

    const {
        type ,
        data = {} ,
        url ,
        cb
    } = options ;

    // {username:'yy' , userpwd : 123}    =>   username=yy&userpwd=123
    let str = '' ;
    // 遍历data
    for(let key in data) {
        str += `${key}=${data[key]}&` ;
    }
    str = str.substring(0,str.length-1) ;
    console.log(str);


    const xhr = new XMLHttpRequest();
    if (type === 'get') {
        xhr.open(type, url + '?' + str , true);
        xhr.send();
    } else {
        xhr.open('post' , url , true) ;
        // 设置一个请求头  --- 定义数据格式
        xhr.setRequestHeader('content-type' , 'application/x-www-form-urlencoded');
        xhr.send(str) ;
    }


    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            let data = xhr.responseText;
            data = JSON.parse(data);
            cb(data);
        }
    }
}